import React, { Component } from 'react'

// 创建context对象
const MyContext = React.createContext()

export default class A extends Component {
    state = { username: '张三' }
    
    render() {
        let { username } = this.state;
        return (
            <div style={{width:'500px',backgroundColor:'orange',padding:'5px'}}>
                <h3>我是A组件</h3>
                <h4>我的用户名：{ username }</h4>
                <MyContext.Provider value={username}>
                    <B />
                </MyContext.Provider>
            </div>
        )
    }
}

class B extends Component {
    render() {
        return (
            <div style={{width:'100%',backgroundColor:'skyblue',padding:'5px'}}>
                <h3 >我是B组件</h3>
                <C />
                <br />
                <D />
            </div>
        )
    }
}

class C extends Component {

    // 声明接收context
    static contextType = MyContext;
    render() {
        return (
            <div style={{width:'100%',backgroundColor:'gray',padding:'5px'}}>
                <h3 >我是C组件</h3>
                <h4>我从A组件接收到的用户名：{ this.context }</h4>
            </div>
        )
    }
}

function D () {
    return (
        <div style={{width:'100%',backgroundColor:'gray',padding:'5px'}}>
            <h3 >我是D组件</h3>
            <h4>我从A组件接收到的用户名：
            <MyContext.Consumer>
                {
                    value => `${value}`
                }
            </MyContext.Consumer>
            </h4>
        </div>
    )       
}
